package com.lzxr.test.servlet;


import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import com.lzxr.test.entity.R;
import com.lzxr.test.utils.FileDownloader;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.*;


public class DownloadServlet extends HttpServlet {

    private static final int CHUNK_SIZE = 1024 * 1024; // 1MB
    private static final int NUM_THREADS = 4; // 4 threads

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 测试用的 url
        // String fileUrl = "http://download.lzxr.vip/1.png";

        String fileUrl = req.getParameter("url");
        String localFilePath = StrUtil.subAfter(fileUrl, StrPool.SLASH, true);
        String fileName = "";

        try {
            fileName = FileDownloader.download(fileUrl, localFilePath);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        resp.sendRedirect("/fileDownload.jsp?filePath="+fileName);
    }

}
